package ctrconfig

import (
    "cloud_worm/util/umodels/mysqldb/dbmanager"
    "cloud_worm/util/umodels/mysqldb"
    "cloud_worm/util/uhttp"
    "github.com/astaxie/beego/logs"
    "fmt"
    "crypto/md5"
    "time"
    "encoding/hex"
)

type TokenController struct {
    LoginCtr
}

func (t *TokenController) Get() {
    t.Manager()

    offset, limit := t.DealPage()
    status, err := t.GetInt("status", mysqldb.StatusAll)
    token := t.GetString("token", mysqldb.SelectStrAll)
    name := t.GetString("name", mysqldb.SelectStrAll)

    to := &dbmanager.Token{}
    count, err := to.Count(status, name, token)
    if err != nil {
        logs.Warn(fmt.Sprintf("TokenController select count error: %s", err.Error()))
        data := map[string]interface{}{"total": 0, "data": []dbmanager.Token{}}
        t.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeSystemErr, "get count error.", data)
        t.ServeJSON()
        return
    }
    if count == 0 {
        data := map[string]interface{}{"total": count, "data": []dbmanager.Token{}}
        t.Data["json"] = uhttp.CreateOkResponse(data)
        t.ServeJSON()
        return
    }

    tokens, err := to.Select(offset, limit, status, name, token)
    if err != nil {
        logs.Warn(fmt.Sprintf("TokenController select token error: %s", err.Error()))
        data := map[string]interface{}{"total": 0, "data": []dbmanager.Token{}}
        t.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeSystemErr, "select error.", data)
        t.ServeJSON()
        return
    }

    data := map[string]interface{}{"total": count, "data": tokens}
    t.Data["json"] = uhttp.CreateOkResponse(data)
    t.ServeJSON()
    return
}

func (t *TokenController) Create() {
    t.Manager()

    type InputInfo struct {
        Name        string          `json:"name"`
    }
    var input InputInfo
    if err := t.Unmarshal(&input); err != nil {
        t.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeReqBodyErr, err.Error(), nil)
        t.ServeJSON()
        return
    }
    if input.Name == "" {
        logs.Warn(fmt.Sprintf("TokenController create input name error."))
        t.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeParamErr, "input name error.", nil)
        t.ServeJSON()
        return
    }

    // 计算md5的token值
    md5Ctx := md5.New()
    md5Ctx.Write([]byte(fmt.Sprintf("%d %s", time.Now().Unix(), input.Name)))
    tokenStr := hex.EncodeToString(md5Ctx.Sum(nil))

    token := &dbmanager.Token{
        Token: tokenStr,
        Name: input.Name,
        Created: time.Now().Unix(),
        Status: mysqldb.StatusValid,
    }
    token.Updated = time.Now().Unix()

    err := token.Insert()
    if err != nil {
        logs.Error(fmt.Sprintf("TokenController insert error: %s", err.Error()))
        t.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeSystemErr, "insert error.", nil)
        t.ServeJSON()
        return
    }

    t.Data["json"] = uhttp.CreateOkResponse(nil)
    t.ServeJSON()
    return
}

func (t *TokenController) Edit() {
    t.Manager()

    type InputInfo struct {
        Id          int64           `json:"id"`
        Name        string          `json:"name"`
        Status      int             `json:"status"`
    }
    var input InputInfo
    if err := t.Unmarshal(&input); err != nil {
        t.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeReqBodyErr, err.Error(), nil)
        t.ServeJSON()
        return
    }

    if input.Name == "" {
        logs.Warn(fmt.Sprintf("TokenController edit input name error."))
        t.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeParamErr, "input name error.", nil)
        t.ServeJSON()
        return
    }
    if input.Status != mysqldb.StatusValid && input.Status != mysqldb.StatusInvalid {
        logs.Warn(fmt.Sprintf("TokenController edit input status error: %d.", input.Status))
        t.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeParamErr, "input status error.", nil)
        t.ServeJSON()
        return
    }
    token := &dbmanager.Token{
        Id: input.Id,
    }
    err := token.Read("id")
    if err != nil {
        logs.Warn(fmt.Sprintf("TokenController edit input id error: %s.", err.Error()))
        t.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeParamErr, "input id error.", nil)
        t.ServeJSON()
        return
    }

    token.Updated = time.Now().Unix()
    token.Name = input.Name
    token.Status = input.Status
    err = token.Update("status", "name", "updated")
    if err != nil {
        logs.Warn(fmt.Sprintf("TokenController updated error: %s.", err.Error()))
        t.Data["json"] = uhttp.CreateErrResponse(uhttp.RespCodeSystemErr, "updated error.", nil)
        t.ServeJSON()
        return
    }

    t.Data["json"] = uhttp.CreateOkResponse(nil)
    t.ServeJSON()
    return
}